﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms.DataVisualization.Charting;
using System.Timers;
using System.IO;
using Microsoft.Win32;

namespace BDSim
{
    /// <summary>
    /// UserMonitorView.xaml 的交互逻辑
    /// </summary>
    public partial class OrbitReportView : UserControl, ILayoutContent
    {
        #region//构造函数
        public OrbitReportView()
        {
            InitializeComponent();
        }

        #endregion

        #region//成员/属性

        /// <summary>
        /// 轨道仿真数据
        /// </summary>
        List<OrbitSimData> OrbitPVList = new List<OrbitSimData>();

        string chk_imagePath = string.Format("{0}\\Resources\\Images\\chk_checked.png", Directory.GetCurrentDirectory());//取得选择图片的绝对路径

        string unchk_imagePath = string.Format("{0}\\Resources\\Images\\chk_unchecked.png", Directory.GetCurrentDirectory());//取得未选择图片的绝对路径

        #endregion

        #region// 数据处理方法

        /// <summary>
        /// 窗口加载函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //获取轴的间隔为1个刻度
            chart2.ChartAreas[0].AxisX.Interval = 1;
            //设置表格横坐标的最小刻度为小时
            chart2.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
            //设置横坐标标签的格式为：年月日时分秒
            chart2.ChartAreas[0].AxisX.LabelStyle.Format = "G";
            //启用表格可缩放功能
            chart2.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
        }

        /// <summary>
        /// 初始化表格，设置各曲线参数
        /// </summary>
        /// <param name="chartType"></param>
        /// <param name="satName"></param>
        public void InitCharts(string satName, List<OrbitSimData> orbitDataList)
        {
            Series SatPosX = new Series("X方向位置曲线(m)") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.Red };
            Series SatPosY = new Series("Y方向位置曲线(m)") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.Green };
            Series SatPosZ = new Series("Z方向位置曲线(m)") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.Blue };
            Series SatPosVx = new Series("X方向速度曲线(m/s)") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.PaleVioletRed, YAxisType = AxisType.Secondary };
            Series SatPosVy = new Series("Y方向速度曲线(m/s)") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.GreenYellow, YAxisType = AxisType.Secondary };
            Series SatPosVz = new Series("Z方向速度曲线(m/s)") { ChartType = SeriesChartType.FastLine, Color = System.Drawing.Color.BlueViolet, YAxisType = AxisType.Secondary };
            chart2.Series.Add(SatPosX);
            chart2.Series.Add(SatPosY);
            chart2.Series.Add(SatPosZ);
            chart2.Series.Add(SatPosVx);
            chart2.Series.Add(SatPosVy);
            chart2.Series.Add(SatPosVz);
            SetLegend(chart2);
            //注册表格视角改变时的事件
            chart2.AxisViewChanged += new EventHandler<ViewEventArgs>(AxisViewChangedEvent);
            //注册表格选择区域改变时的事件
            chart2.SelectionRangeChanged += new EventHandler<CursorEventArgs>(SelectionChangedEvent);
            chart2.ChartAreas[0].AxisX.Title = "仿真时间";
            chart2.ChartAreas[0].AxisY.Title = "卫星轨道位置(m)";
            chart2.ChartAreas[0].AxisY2.Title = "卫星轨道速度(m/s)";
            //获取卫星的轨道数据集合
            OrbitPVList = orbitDataList;
            chart2.Titles.Add("卫星【" + satName + "】轨道：J2000坐标系");
            ProtractSatOrbit();
            UpdateFlag.Visibility = System.Windows.Visibility.Collapsed;
        }

        /// <summary>
        /// 绘制卫星轨道
        /// </summary>
        void ProtractSatOrbit()
        {
            //复位表格
            ResetChart2();
            for (int i = 0; i < OrbitPVList.Count; i++)
            {
                NodePosVel tempPV = new NodePosVel();
                //选择ECI轨道数据类型时
                if (rdbECI.IsChecked == true)
                {
                    chart2.Titles[0].Text = chart2.Titles[0].Text.Replace("CGCS2000", "J2000");
                    tempPV = OrbitPVList[i].SatPV_ECI;
                }
                //选择ECF轨道数据类型时
                else if (rdbECF.IsChecked == true)
                {
                    chart2.Titles[0].Text = chart2.Titles[0].Text.Replace("J2000", "CGCS2000");
                    tempPV = OrbitPVList[i].SatPV_ECF;
                }
                //把轨道历元转化为日期时间
                DateTime newTime = tempPV.Epoch.ToDateTime();
                chart2.Series[0].Points.AddXY(newTime, tempPV.X);
                chart2.Series[1].Points.AddXY(newTime, tempPV.Y);
                chart2.Series[2].Points.AddXY(newTime, tempPV.Z);
                chart2.Series[3].Points.AddXY(newTime, tempPV.VX);
                chart2.Series[4].Points.AddXY(newTime, tempPV.VY);
                chart2.Series[5].Points.AddXY(newTime, tempPV.VZ);
            }
        }

        /// <summary>
        /// 复位表格
        /// </summary>
        void ResetChart2()
        {
            for (int i = 0; i < chart2.Series.Count; i++)
            {
                //清除表格所有曲线的所有点
                chart2.Series[i].Points.Clear();
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void ReleaseData()
        {
            //清空所有集合数据
            ResetChart2();
        }

        #endregion

        #region//表格控制方法
        /// <summary>
        /// 表格选择区域变化时执行的事件
        /// </summary>
        /// <param name="e"></param>
        void SelectionChangedEvent(object sender, CursorEventArgs e)
        {
            if (e.Axis.AxisName == AxisName.X)
            {
                double TimeOfDay = e.Axis.ScaleView.ViewMaximum - e.Axis.ScaleView.ViewMinimum;
                //横坐标显示的时间范围在一分钟以内，坐标间隔类型设置为“秒”
                if (TimeOfDay * 86400 <= 60)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Seconds;
                }
                //横坐标显示的时间范围在一小时以内，坐标间隔类型设置为“分钟”
                else if (TimeOfDay * 24 <= 1)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Minutes;
                }
                //横坐标显示的时间范围在两天以内，坐标间隔类型设置为“小时”
                else if (TimeOfDay <= 2)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Hours;
                }
                //横坐标显示的时间范围在60以内，坐标间隔类型设置为“天”
                else if (TimeOfDay < 60)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Days;
                }
            }
        }
        
        /// <summary>
        /// 缩小表格视角大小时执行的事件
        /// </summary>
        /// <param name="e">事件参数</param>
        void AxisViewChangedEvent(object sender, ViewEventArgs e)
        {
            if (e.Axis.AxisName == AxisName.X)
            {
                double TimeOfDay = e.Axis.ScaleView.ViewMaximum - e.Axis.ScaleView.ViewMinimum;
                //横坐标显示的时间范围在一分钟以内，坐标间隔类型设置为“秒”
                if (TimeOfDay * 86400 <= 60)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Seconds;
                }
                //横坐标显示的时间范围在一小时以内，坐标间隔类型设置为“分钟”
                else if (TimeOfDay * 24 <= 1)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Minutes;
                }
                //横坐标显示的时间范围在两天以内，坐标间隔类型设置为“小时”
                else if (TimeOfDay <= 2)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Hours;
                }
                //横坐标显示的时间范围在60以内，坐标间隔类型设置为“天”
                else if (TimeOfDay < 60)
                {
                    e.ChartArea.AxisX.IntervalType = DateTimeIntervalType.Days;
                }
            }
        }

        /// <summary>
        /// 用于选择是否显示当前曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Chart_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            System.Windows.Forms.DataVisualization.Charting.HitTestResult result = ((Chart)sender).HitTest(e.X, e.Y);
            if (result != null && result.Object != null)
            {
                // When user hits the LegendItem
                if (result.Object is LegendItem)
                {
                    // Legend item result
                    LegendItem legendItem = (LegendItem)result.Object;

                    // series item selected
                    Series selectedSeries = (Series)legendItem.Tag;

                    if (selectedSeries != null)
                    {
                        if (selectedSeries.Enabled)
                        {
                            selectedSeries.Enabled = false;
                            if (File.Exists(unchk_imagePath))
                            {
                                legendItem.Cells[0].Image = unchk_imagePath;
                            }
                        }
                        else
                        {
                            selectedSeries.Enabled = true;
                            if (File.Exists(chk_imagePath))
                            {
                                legendItem.Cells[0].Image = chk_imagePath;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 保存表格当前图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            //  进行当前路径保存
            string currentDirectory = Directory.GetCurrentDirectory();

            // Create a new save file dialog
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            // Sets the current file name filter string, which determines 
            // the choices that appear in the "Save as file type" or 
            // "Files of type" box in the dialog box.
            saveFileDialog1.Filter = "Bitmap (*.bmp)|*.bmp|JPEG (*.jpg)|*.jpg|EMF (*.emf)|*.emf|PNG (*.png)|*.png|GIF (*.gif)|*.gif|TIFF (*.tif)|*.tif";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            // Set image file format
            if (saveFileDialog1.ShowDialog() == true)
            {
                ChartImageFormat format = ChartImageFormat.Bmp;

                if (saveFileDialog1.FileName.EndsWith("bmp"))
                {
                    format = ChartImageFormat.Bmp;
                }
                else if (saveFileDialog1.FileName.EndsWith("jpg"))
                {
                    format = ChartImageFormat.Jpeg;
                }
                else if (saveFileDialog1.FileName.EndsWith("emf"))
                {
                    format = ChartImageFormat.Emf;
                }
                else if (saveFileDialog1.FileName.EndsWith("gif"))
                {
                    format = ChartImageFormat.Gif;
                }
                else if (saveFileDialog1.FileName.EndsWith("png"))
                {
                    format = ChartImageFormat.Png;
                }
                else if (saveFileDialog1.FileName.EndsWith("tif"))
                {
                    format = ChartImageFormat.Tiff;
                }
                //else if (saveFileDialog1.FileName.EndsWith("svg"))
                //{
                //    format = ChartImageFormat.Svg;
                //}

                // Save image
                chart2.SaveImage(saveFileDialog1.FileName, format);
            }

            Directory.SetCurrentDirectory(currentDirectory);
        }

        /// <summary>
        /// 根据表格中的series建立自定义legend图例列表，靠表格下方呈横排列
        /// </summary>
        /// <param name="chart"></param>
        void SetLegend(Chart chart)
        {
            chart.Legends.Add(new Legend() { Enabled = false });
            chart.Legends.Add(new Legend() { LegendStyle = LegendStyle.Row, Docking = Docking.Bottom, Alignment = System.Drawing.StringAlignment.Center });
            for (int i = 0; i < chart.Series.Count; i++)
            {
                chart.Legends[1].CustomItems.Add(new LegendItem() { Enabled = true, Color = chart.Series[i].Color, BorderColor = System.Drawing.Color.White, BorderWidth = 2});
                chart.Legends[1].CustomItems[i].Tag = chart.Series[i];
                chart.Legends[1].CustomItems[i].Cells.Add(new LegendCell() { CellType = LegendCellType.Image, Image = chk_imagePath, ImageTransparentColor = System.Drawing.Color.Red });
                chart.Legends[1].CustomItems[i].Cells.Add(LegendCellType.SeriesSymbol, "", System.Drawing.ContentAlignment.MiddleCenter);
                chart.Legends[1].CustomItems[i].Cells.Add(LegendCellType.Text, chart.Series[i].Name, System.Drawing.ContentAlignment.MiddleCenter);
                
                //chart.Legends.Add(new Legend() { Enabled = true, Title = chart.Series[i].Name });
                //chart.Legends[0].CustomItems[i].Cells.Add(
            }
        }
        #endregion

        #region//界面逻辑
        /// <summary>
        /// 选择不同坐标系时执行重绘表格事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdb_Checked(object sender, RoutedEventArgs e)
        {
            ProtractSatOrbit();
        }

        /// <summary>
        /// 选择是否显示表格网格事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            if (((CheckBox)sender).IsChecked == true)
            {
                chart2.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.Transparent;
                chart2.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.Transparent;
                chart2.ChartAreas[0].AxisY2.MajorGrid.LineColor = System.Drawing.Color.Transparent;
            }
            else
            {
                chart2.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.Black;
                chart2.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.Black;
                chart2.ChartAreas[0].AxisY2.MajorGrid.LineColor = System.Drawing.Color.Black;
            }
        }
        #endregion
    }
}
